package org.example.Service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.Dao.EmpDao;
import org.example.JavaBean.Emp;
import org.example.Service.EmpService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:EmpServiceImpl
 * @Date:2025/7/29 15:10
 */
@Service
public class EmpServiceImpl implements EmpService {
    @Resource
    private EmpDao empDao;

    @Override
    public JsonResult findAll() {
        List<Emp> all = empDao.findAll();
        if (all == null) {
            return ResultTool.fail(200, "查找错误");
        } else {
            return ResultTool.success(all);
        }
    }

    @Override
    public JsonResult findByEname(String ename) {
        List<Emp> byEname = empDao.findByEname("%" + ename + "%");
        if (byEname == null) {
            return ResultTool.fail(500, "查询无结果");
        } else {
            return ResultTool.success(byEname);
        }
    }

    @Override
    public JsonResult find() {
        List<Emp> emps = empDao.find();
        if (emps == null) {
            return ResultTool.fail(500, "查找错误");
        } else {
            return ResultTool.success(emps);
        }
    }

    @Override
    public JsonResult findByPage(int page, int size) {
        PageHelper.startPage(page, size);
        List<Emp> list = empDao.findAll();
        PageInfo<Emp> pageInfo = new PageInfo(list);
        return ResultTool.success(pageInfo);
    }

    @Override
    public JsonResult InsertOne(Emp emp) {
        int i = empDao.insert(emp);
        if (i > 0) {
            return ResultTool.success("插入成功");
        } else {
            return ResultTool.fail(500, "插入失败");
        }
    }

    @Override
    public JsonResult delete(int empno) {
        int delete = empDao.delete(empno);
        if (delete > 0) {
            return ResultTool.success("删除成功");
        } else {
            return ResultTool.fail(500, "删除失败");
        }
    }

    @Override
    @Transactional
    public JsonResult InsertORDelete( int empno,Emp emp) {
        int i = empDao.delete(empno);
        if (i > 0) {
            int i1 = empDao.insert(emp);
            if (i1 > 0) {
                System.out.println(ResultTool.success("插入成功"));
            } else {
                System.out.println(ResultTool.fail(500, "插入失败"));
            }
            return ResultTool.success("删除成功");
        }
        return ResultTool.fail(500, "删除失败");
    }
}
